<script setup lang="ts">
import { ref, onMounted, reactive, h, computed } from 'vue'
import {
  Card as ACard,
  Table as ATable,
  Button as AButton,
  Modal as AModal,
  Form as AForm,
  FormItem as AFormItem,
  Input as AInput,
  InputNumber as AInputNumber,
  Upload as AUpload,
  message as AMessage,
  Popconfirm as APopconfirm,
  Switch as ASwitch,
  Divider as ADivider,
  Tag as ATag,
  Tooltip as ATooltip,
  Spin as ASpin,
  Row as ARow,
  Col as ACol,
  Select as ASelect,
  SelectOption as ASelectOption,
  DatePicker as ADatePicker,
} from 'ant-design-vue'
import type { RuleObject } from 'ant-design-vue/es/form'
import type { ButtonProps } from 'ant-design-vue/es/button'
import {
  CloudUploadOutlined,
  DeleteOutlined,
  EditOutlined,
  EyeOutlined,
  DownloadOutlined,
  InfoCircleOutlined,
  UploadOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  QuestionCircleOutlined,
  ReloadOutlined,
  CopyOutlined,
  QrcodeOutlined,
} from '@ant-design/icons-vue'
import axios from 'axios'
import { formatDate } from '@/utils/format'
import QRCode from 'qrcode'
import { useUserStore } from '@/stores/user'
import { addVersion, deleteVersion, getVersionList, updateVersion } from '@/api/manger'

// 使用用户存储
const userStore = useUserStore()

// 定义版本信息接口
interface VersionInfo {
  id: number
  version: string
  platform: string
  downloadUrl: string
  description: string
  forceUpdate: number
  releaseTime: string
  createTime: string
  updateTime: string
  status: number
}

// 表格列定义
const columns = [
  {
    title: '版本号',
    dataIndex: 'version',
    key: 'version',
  },
  {
    title: '平台',
    dataIndex: 'platform',
    key: 'platform',
    customRender: ({ text }) => {
      return h(ATag, { color: text === 'android' ? 'green' : 'blue' }, { default: () => text })
    },
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    customRender: ({ text }) => {
      return h(
        ATag,
        { color: text === 1 ? 'success' : 'error' },
        { default: () => (text === 1 ? '已发布' : '已下架') },
      )
    },
  },
  {
    title: '强制更新',
    dataIndex: 'forceUpdate',
    key: 'forceUpdate',
    customRender: ({ text }) => {
      return h(
        ATag,
        { color: text === 1 ? 'warning' : 'default' },
        { default: () => (text === 1 ? '是' : '否') },
      )
    },
  },
  {
    title: '发布时间',
    dataIndex: 'releaseTime',
    key: 'releaseTime',
    customRender: ({ text }) => formatDate(text),
  },
  {
    title: '操作',
    key: 'action',
    customRender: ({ record }) => {
      return h('div', { class: 'action-buttons' }, [
        h(
          AButton,
          {
            type: 'text',
            onClick: () => viewVersionDetail(record),
          },
          {
            icon: () => h(EyeOutlined),
            default: () => '详情',
          },
        ),
        h(
          AButton,
          {
            type: 'text',
            onClick: () => editVersion(record),
          },
          {
            icon: () => h(EditOutlined),
            default: () => '编辑',
          },
        ),
        h(
          AButton,
          {
            type: 'text',
            onClick: () => toggleVersionStatus(record, record.status === 1 ? 0 : 1),
          },
          {
            icon: () => h(record.status === 1 ? CloseCircleOutlined : CheckCircleOutlined),
            default: () => (record.status === 1 ? '下架' : '发布'),
          },
        ),
        h(
          APopconfirm,
          {
            title: '确定要删除此版本吗？',
            onConfirm: () => handleDeleteVersion(record.id),
          },
          {
            default: () =>
              h(
                AButton,
                {
                  type: 'text',
                  danger: true,
                },
                {
                  icon: () => h(DeleteOutlined),
                  default: () => '删除',
                },
              ),
          },
        ),
      ])
    },
  },
]

// 表格加载状态
const loading = ref(false)

// 版本列表
const versionList = ref<VersionInfo[]>([])

// 当前最新版本
const latestVersion = ref<VersionInfo | null>(null)

// 二维码相关
const qrcodeModalVisible = ref(false)
const qrcodeUrl = ref('')
const qrcodeTitle = ref('')

// 当前版本详情
const currentVersionDetail = ref<VersionInfo>({} as VersionInfo)

// 详情模态框可见性
const detailModalVisible = ref(false)
const detailLoading = ref(false)

// 表单模态框可见性
const formModalVisible = ref(false)
const formLoading = ref(false)
const isEdit = ref(false)
const currentId = ref<number | null>(null)

// 模态框标题
const modalTitle = computed(() => (isEdit.value ? '编辑版本' : '添加新版本'))

// 表单状态
const formState = reactive({
  version: '',
  platform: 'android',
  downloadUrl: '',
  description: '',
  forceUpdate: 0,
  releaseTime: '',
  status: 1,
})

// 表单规则
const rules = {
  version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
  platform: [{ required: true, message: '请选择平台', trigger: 'change' }],
  downloadUrl: [{ required: true, message: '请输入下载链接', trigger: 'blur' }],
  description: [{ required: true, message: '请输入更新日志', trigger: 'blur' }],
} as Record<string, RuleObject[]>

// 表单引用
const formRef = ref()

// 获取版本列表
const fetchVersionList = async () => {
  loading.value = true
  try {
    const response = await getVersionList()
    if (response.data.code === 200) {
      versionList.value = response.data.data

      // 找出最新版本（状态为已发布的最高版本号）
      const publishedVersions = versionList.value.filter((v) => v.status === 1)
      if (publishedVersions.length > 0) {
        // 按版本号排序，获取最新版本
        latestVersion.value = publishedVersions.sort((a, b) => {
          const vA = a.version.split('.').map(Number)
          const vB = b.version.split('.').map(Number)
          for (let i = 0; i < Math.max(vA.length, vB.length); i++) {
            const numA = i < vA.length ? vA[i] : 0
            const numB = i < vB.length ? vB[i] : 0
            if (numA !== numB) return numB - numA // 降序排列
          }
          return 0
        })[0]
      } else {
        latestVersion.value = null
      }
    } else {
      AMessage.error(response.data.message || '获取版本列表失败')
    }
  } catch (error) {
    console.error('获取版本列表出错:', error)
    AMessage.error('获取版本列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 查看版本详情
const viewVersionDetail = (record: VersionInfo) => {
  currentVersionDetail.value = { ...record }
  detailModalVisible.value = true
}

// 编辑版本
const editVersion = (record: VersionInfo) => {
  isEdit.value = true
  currentId.value = record.id

  // 填充表单数据
  Object.keys(formState).forEach((key) => {
    if (key in record) {
      formState[key] = record[key]
    }
  })

  formModalVisible.value = true
}

// 添加新版本
const addNewVersion = () => {
  isEdit.value = false
  currentId.value = null

  // 重置表单
  Object.keys(formState).forEach((key) => {
    if (key === 'platform') {
      formState[key] = 'android'
    } else if (key === 'forceUpdate' || key === 'status') {
      formState[key] = 0
    } else {
      formState[key] = ''
    }
  })

  // 设置默认发布时间为当前时间
  formState.releaseTime = formatDate(new Date())

  formModalVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    formLoading.value = true

    // 准备提交的数据
    const params: any = { ...formState }

    // 如果是编辑模式，添加ID
    if (isEdit.value && currentId.value) {
      params.id = currentId.value
    }

    const response = isEdit.value ? await updateVersion(params) : await addVersion(params)

    if (response.data.code === 200 && response.data.data) {
      AMessage.success(isEdit.value ? '更新版本成功' : '添加新版本成功')
      formModalVisible.value = false
      fetchVersionList() // 刷新列表
    } else {
      AMessage.error(response.data.message || (isEdit.value ? '更新版本失败' : '添加新版本失败'))
    }
  } catch (error) {
    console.error(isEdit.value ? '更新版本出错:' : '添加新版本出错:', error)
    AMessage.error(isEdit.value ? '更新版本失败' : '添加新版本失败')
  } finally {
    formLoading.value = false
  }
}

// 切换版本状态（发布/下架）
const toggleVersionStatus = async (record: VersionInfo, newStatus: number) => {
  try {
    const response = await updateVersion({
      id: record.id,
      status: newStatus,
    })

    if (response.data.code === 200 && response.data.data) {
      AMessage.success(newStatus === 1 ? '版本发布成功' : '版本下架成功')
      fetchVersionList() // 刷新列表
    } else {
      AMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    console.error('切换版本状态出错:', error)
    AMessage.error('操作失败，请稍后重试')
  }
}

// 删除版本
const handleDeleteVersion = async (id: number) => {
  try {
    const response = await deleteVersion(id)

    if (response.data.code === 200 && response.data.data) {
      AMessage.success('删除版本成功')
      fetchVersionList() // 刷新列表
    } else {
      AMessage.error(response.data.message || '删除版本失败')
    }
  } catch (error) {
    console.error('删除版本出错:', error)
    AMessage.error('删除版本失败，请稍后重试')
  }
}

// 上传APK文件
const handleFileUpload = async (info) => {
  const { file, fileList } = info

  if (file.status === 'uploading') {
    return
  }

  if (file.status === 'done') {
    if (file.response && file.response.code === 200) {
      const downloadUrl = file.response.data
      formState.downloadUrl = downloadUrl
      AMessage.success('文件上传成功')
    } else {
      AMessage.error(file.response?.message || '文件上传失败')
    }
  } else if (file.status === 'error') {
    AMessage.error('文件上传失败')
  }
}

// 复制下载链接
const copyDownloadUrl = (url: string) => {
  navigator.clipboard
    .writeText(url)
    .then(() => {
      AMessage.success('下载链接已复制到剪贴板')
    })
    .catch(() => {
      AMessage.error('复制失败，请手动复制')
    })
}

// 生成二维码
const generateQRCode = (url: string) => {
  qrcodeTitle.value = '扫描下载APP'

  QRCode.toDataURL(url, { width: 300 })
    .then((dataUrl) => {
      qrcodeUrl.value = dataUrl
      qrcodeModalVisible.value = true
    })
    .catch((err) => {
      console.error('生成二维码失败:', err)
      AMessage.error('生成二维码失败')
    })
}

// 打开下载链接
const openDownloadUrl = (url: string) => {
  window.open(url, '_blank')
}

// 通过设置location跳转
const redirectToUrl = (url: string) => {
  window.location.href = url
}

// 初始化
onMounted(() => {
  fetchVersionList()
})
</script>

<template>
  <div class="version-manage">
    <ACard class="version-card" title="版本管理">
      <template #extra>
        <div class="toolbar">
          <AButton type="primary" @click="addNewVersion">
            <CloudUploadOutlined /> 添加新版本
          </AButton>
          <AButton @click="fetchVersionList"> <ReloadOutlined /> 刷新 </AButton>
        </div>
      </template>

      <!-- 最新版本信息卡片 -->
      <ACard v-if="latestVersion" class="latest-version-info" title="当前最新版本">
        <div class="latest-version-content">
          <div class="version-info">
            <p>
              <strong>版本号:</strong> {{ latestVersion.version }}
              <ATag :color="latestVersion.platform === 'android' ? 'green' : 'blue'">
                {{ latestVersion.platform }}
              </ATag>
            </p>
            <p>
              <strong>更新类型:</strong>
              <ATag :color="latestVersion.forceUpdate === 1 ? 'warning' : 'default'">
                {{ latestVersion.forceUpdate === 1 ? '强制更新' : '非强制' }}
              </ATag>
            </p>
            <p><strong>发布时间:</strong> {{ formatDate(latestVersion.releaseTime) }}</p>
            <div class="update-log">
              <h4>更新日志:</h4>
              <p>{{ latestVersion.description }}</p>
            </div>
          </div>
          <div class="version-actions">
            <AButton type="primary" @click="() => redirectToUrl(latestVersion.downloadUrl)">
              <DownloadOutlined /> 下载APK
            </AButton>
            <AButton @click="() => copyDownloadUrl(latestVersion.downloadUrl)">
              <CopyOutlined /> 复制链接
            </AButton>
            <AButton @click="() => generateQRCode(latestVersion.downloadUrl)">
              <QrcodeOutlined /> 生成二维码
            </AButton>
          </div>
        </div>
      </ACard>

      <!-- 版本列表表格 -->
      <ATable
        :columns="columns"
        :data-source="versionList"
        :loading="loading"
        :pagination="{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
        }"
        :row-key="(record) => record.id"
      />
    </ACard>

    <!-- 添加/编辑版本模态框 -->
    <AModal
      :title="modalTitle"
      :visible="formModalVisible"
      :confirm-loading="formLoading"
      @ok="submitForm"
      @cancel="() => (formModalVisible = false)"
      width="700px"
    >
      <AForm ref="formRef" :model="formState" :rules="rules" layout="vertical">
        <ARow :gutter="16">
          <ACol :span="12">
            <AFormItem label="版本号" name="version">
              <AInput v-model:value="formState.version" placeholder="例如: 1.0.0" />
              <div class="form-item-help">请使用语义化版本号，如 1.0.0</div>
            </AFormItem>
          </ACol>
          <ACol :span="12">
            <AFormItem label="平台" name="platform">
              <ASelect v-model:value="formState.platform">
                <ASelectOption value="android">Android</ASelectOption>
                <ASelectOption value="ios">iOS</ASelectOption>
              </ASelect>
            </AFormItem>
          </ACol>
        </ARow>

        <AFormItem label="下载链接" name="downloadUrl">
          <AInput v-model:value="formState.downloadUrl" placeholder="请输入APK下载链接" />
          <div class="form-item-help">您也可以上传APK文件，系统会自动生成下载链接</div>
        </AFormItem>

        <AFormItem label="上传APK文件">
          <AUpload
            name="file"
            :custom-request="handleFileUpload"
            :show-upload-list="true"
            :max-count="1"
            accept=".apk"
          >
            <AButton> <UploadOutlined /> 点击上传APK </AButton>
          </AUpload>
          <div class="upload-info">支持的文件类型: .apk，最大文件大小: 100MB</div>
        </AFormItem>

        <AFormItem label="更新日志" name="description">
          <AInput.TextArea
            v-model:value="formState.description"
            :rows="4"
            placeholder="请输入本次更新的内容"
          />
        </AFormItem>

        <ARow :gutter="16">
          <ACol :span="12">
            <AFormItem label="发布时间" name="releaseTime">
              <ADatePicker
                v-model:value="formState.releaseTime"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </AFormItem>
          </ACol>
          <ACol :span="12">
            <AFormItem label="是否强制更新">
              <ASwitch
                v-model:checked="formState.forceUpdate"
                :checked-value="1"
                :unchecked-value="0"
              />
              <span class="switch-label">
                {{ formState.forceUpdate === 1 ? '强制更新' : '非强制' }}
              </span>
            </AFormItem>
          </ACol>
        </ARow>

        <ARow :gutter="16">
          <ACol :span="12">
            <AFormItem label="发布状态">
              <ASwitch v-model:checked="formState.status" :checked-value="1" :unchecked-value="0" />
              <span class="switch-label">
                {{ formState.status === 1 ? '立即发布' : '暂不发布' }}
              </span>
            </AFormItem>
          </ACol>
        </ARow>
      </AForm>
    </AModal>

    <!-- 版本详情模态框 -->
    <AModal
      title="版本详情"
      :visible="detailModalVisible"
      @cancel="() => (detailModalVisible = false)"
      :footer="null"
      width="600px"
    >
      <ASpin :spinning="detailLoading">
        <div class="version-detail">
          <div class="detail-item">
            <span class="detail-label">版本号:</span>
            <span class="detail-value">{{ currentVersionDetail.version }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">平台:</span>
            <span class="detail-value">
              <ATag :color="currentVersionDetail.platform === 'android' ? 'green' : 'blue'">
                {{ currentVersionDetail.platform }}
              </ATag>
            </span>
          </div>
          <div class="detail-item">
            <span class="detail-label">状态:</span>
            <span class="detail-value">
              <ATag :color="currentVersionDetail.status === 1 ? 'success' : 'error'">
                {{ currentVersionDetail.status === 1 ? '已发布' : '已下架' }}
              </ATag>
            </span>
          </div>
          <div class="detail-item">
            <span class="detail-label">更新类型:</span>
            <span class="detail-value">
              <ATag :color="currentVersionDetail.forceUpdate === 1 ? 'warning' : 'default'">
                {{ currentVersionDetail.forceUpdate === 1 ? '强制更新' : '非强制' }}
              </ATag>
            </span>
          </div>
          <div class="detail-item">
            <span class="detail-label">发布时间:</span>
            <span class="detail-value">{{ formatDate(currentVersionDetail.releaseTime) }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">创建时间:</span>
            <span class="detail-value">{{ formatDate(currentVersionDetail.createTime) }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">下载链接:</span>
            <span class="detail-value download-link">
              <a :href="currentVersionDetail.downloadUrl" target="_blank">
                {{ currentVersionDetail.downloadUrl }}
              </a>
              <AButton
                size="small"
                type="link"
                @click="() => copyDownloadUrl(currentVersionDetail.downloadUrl)"
              >
                复制
              </AButton>
            </span>
          </div>
          <div class="detail-item update-log-detail">
            <span class="detail-label">更新日志:</span>
            <div class="detail-value log-content">
              {{ currentVersionDetail.description }}
            </div>
          </div>

          <div class="detail-actions">
            <AButton
              type="primary"
              @click="() => openDownloadUrl(currentVersionDetail.downloadUrl)"
            >
              <DownloadOutlined /> 下载APK
            </AButton>
            <AButton @click="() => generateQRCode(currentVersionDetail.downloadUrl)">
              <QrcodeOutlined /> 生成二维码
            </AButton>
            <AButton @click="() => editVersion(currentVersionDetail)">
              <EditOutlined /> 编辑版本
            </AButton>
            <AButton
              @click="
                () => {
                  detailModalVisible = false
                  toggleVersionStatus(
                    currentVersionDetail,
                    currentVersionDetail.status === 1 ? 0 : 1,
                  )
                }
              "
              :type="currentVersionDetail.status === 0 ? 'primary' : 'default'"
              :danger="currentVersionDetail.status === 1"
            >
              {{ currentVersionDetail.status === 0 ? '发布版本' : '下架版本' }}
            </AButton>
          </div>
        </div>
      </ASpin>
    </AModal>

    <!-- 二维码模态框 -->
    <AModal
      :title="qrcodeTitle"
      :visible="qrcodeModalVisible"
      @cancel="() => (qrcodeModalVisible = false)"
      :footer="null"
      width="350px"
    >
      <div style="text-align: center">
        <img :src="qrcodeUrl" alt="下载二维码" style="width: 300px; height: 300px" />
        <p style="margin-top: 16px">扫描二维码下载APP</p>
      </div>
    </AModal>
  </div>
</template>

<style scoped>
.version-manage {
  padding: 24px;
}

.version-card {
  margin-bottom: 24px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.toolbar {
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.latest-version-info {
  margin-bottom: 24px;
}

.latest-version-content {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 16px;
}

.version-info {
  flex: 1;
  min-width: 250px;
}

.version-info p {
  margin-bottom: 8px;
}

.version-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.update-log h4 {
  margin-bottom: 8px;
  font-weight: 500;
}

.upload-info {
  margin-top: 8px;
  color: #666;
}

.form-item-help {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}

.switch-label {
  margin-left: 8px;
  color: #666;
}

.version-detail {
  padding: 8px;
}

.detail-item {
  margin-bottom: 16px;
  display: flex;
}

.detail-label {
  font-weight: 500;
  width: 100px;
  flex-shrink: 0;
}

.detail-value {
  flex: 1;
}

.download-link {
  word-break: break-all;
  display: flex;
  align-items: center;
  gap: 8px;
}

.update-log-detail {
  flex-direction: column;
}

.log-content {
  margin-top: 8px;
  padding: 12px;
  background-color: #f5f5f5;
  border-radius: 4px;
  white-space: pre-line;
}

.detail-actions {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

@media (max-width: 768px) {
  .latest-version-content {
    flex-direction: column;
  }

  .version-actions {
    flex-direction: row;
    flex-wrap: wrap;
  }

  .detail-item {
    flex-direction: column;
  }

  .detail-label {
    width: 100%;
    margin-bottom: 4px;
  }
}
</style>
